/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.tools.idea.uibuilder.palette;

import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

/**
 * A {@link ListModel} for displaying palette categories in a list.
 * Updates are being generated by a {@link DataModel}.
 */
public class CategoryListModel extends AbstractListModel<Palette.Group> {
  private final List<Palette.Group> myGroups;
  private final List<Integer> myMatchCounts;

  public CategoryListModel() {
    myGroups = new ArrayList<>();
    myMatchCounts = new ArrayList<>();
  }

  public void update(@NotNull List<Palette.Group> groups, @NotNull List<Integer> matchCounts) {
    assert SwingUtilities.isEventDispatchThread() : "Updates must be on EDT";
    myGroups.clear();
    myMatchCounts.clear();

    myGroups.addAll(groups);
    myMatchCounts.addAll(matchCounts);
    fireContentsChanged(this, 0, myGroups.size() - 1);
  }

  public boolean contains(@NotNull Palette.Group group) {
    return myGroups.contains(group);
  }

  @Override
  public int getSize() {
    return myGroups.size();
  }

  public boolean hasExplicitGroups() {
    // The DataModel will always add 1 group: Common or Result
    return getSize() > 1;
  }

  @Override
  public Palette.Group getElementAt(int index) {
    return myGroups.get(index);
  }

  public boolean hasMatchCounts() {
    return !myMatchCounts.isEmpty();
  }

  public int getMatchCountAt(int index) {
    if (myMatchCounts.isEmpty()) {
      return -1;
    }
    return myMatchCounts.get(index);
  }
}
